2 // NSString-FBAdditions.m
5 // Created by Ofri Wolfus on 22/08/06.
6 // Copyright 2006 Ofri Wolfus. All rights reserved.
9 #import "NSString-FBAdditions.h"
11 #import "ConvertUTF.h"
14 @implementation NSString (FBAdditions)
17 * This method attempts to determine the base writing direction of our string.
18 * We do this by looping through our characters until we find the first one that knows its writing direction.
19 * This method will usually get the right direction, unless someone accidentally put a random letter at the
20 * beginning of the string, which has a different writing direction.
21 * But since this will be the user's fault, he'll have to deal with it :)
22 * Anyhow, AppKit also uses this method when displaying bidi text.
24 - (NSWritingDirection)baseWritingDirection {
25 unsigned int len = [self length];
29 NSWritingDirection dir = NSWritingDirectionNatural;
32 * Loop through all our characters, one by one, until we find one which knows its writing direction.
33 * Note: If our string begins with lots of universal characters (characters without a direction), this
34 * could get very inefficient.
36 for (i = 0U; i < len; i++) {
39 // Get a single character
40 uch = (UTF16)CFStringGetCharacterAtIndex((CFStringRef)self, i);
44 // Convert our UniChar (which is UTF16) to FriBidiChar (which is UTF32)
45 if (ConvertUTF16toUTF32((const UTF16**)&u, (u + 1), &f, (f + 1), lenientConversion) == conversionOK) {
46 // Get the type of our character
47 type = fribidi_get_type(fch);
50 if (type == FRIBIDI_TYPE_LTR) {
51 dir = NSWritingDirectionLeftToRight;
56 if (type == FRIBIDI_TYPE_RTL) {
57 dir = NSWritingDirectionRightToLeft;